package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.to.EsSkuInfo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.WareStock;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.fegin.RemoteElasticService;
import com.atguigu.gulimall.product.fegin.WareService;
import com.atguigu.gulimall.product.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private WareService wareService;
    @Autowired
    private RemoteElasticService remoteElasticService;
    @Autowired
    private SpuInfoService spuInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId
     */
    @Override
    public void spuUp(Long spuId) {
        //一个spu有多个sku
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        if (!CollectionUtils.isEmpty(skuInfoEntityList)) {
            ArrayList<EsSkuInfo> resultList = new ArrayList<>();
            //TODO 4.查询当前sku所有可以用来检索的规格属性attrs  attrId attrName attrValue
            //1.根据spu_id查出所有可检索的属性id
            List<ProductAttrValueEntity> searchAttrs = productAttrValueService.getSearchAttrs(spuId);
            log.debug("可检索的属性" + searchAttrs);
            //将属性拷贝到Atts里
            List<EsSkuInfo.Attrs> attrsList = searchAttrs.stream()
                    .map(productAttrValueEntity -> {
                        EsSkuInfo.Attrs attrs = new EsSkuInfo.Attrs();
                        BeanUtils.copyProperties(productAttrValueEntity, attrs);
                        return attrs;
                    })
                    .collect(Collectors.toList());
            //这边直接批量传sku_id，一次性调用远程接口。来查它们的库存
            List<Long> skuIds = skuInfoEntityList.stream()
                    .map(SkuInfoEntity::getSkuId)
                    .collect(Collectors.toList());
            Map<Long, Boolean> stockMap = new HashMap<>();
            try {
                List<WareStock> wareStocks = wareService.getSkuStock(skuIds);
//                stockMap = wareStocks.stream().collect(Collectors.toMap(WareStock::getSkuId, item -> item.getHasStock()));
                if (!CollectionUtils.isEmpty(wareStocks)) {
                    for (WareStock wareStock : wareStocks) {
                        stockMap.put(wareStock.getSkuId(), wareStock.getHasStock());
                    }
                }
                log.debug("库存" + wareStocks);
            } catch (Exception e) {
                log.error("库存服务调用失败，原因:{}", e);
            }
            //将这个转换为map格式
            Map<Long, Boolean> finalStockMap = stockMap;
            List<EsSkuInfo> esSkuInfoList = skuInfoEntityList.stream()
                    .map(skuInfo -> {
                        //把要上架的spu里的商品信息拷贝到新的实体类里面
                        EsSkuInfo esSkuInfo = new EsSkuInfo();
                        BeanUtils.copyProperties(skuInfo, esSkuInfo);
                        //skuPrice
                        esSkuInfo.setSkuPrice(skuInfo.getPrice());
                        //skuImg
                        esSkuInfo.setSkuImg(skuInfo.getSkuDefaultImg());
                        //TODO 1.hasStock  库存(调用库存服务查询)
                        //这边直接批量传sku_id，一次性调用远程接口。来查它们的库存
                        //设置库存信息
                        if (finalStockMap == null) {
                            esSkuInfo.setHasStock(false);
                        } else {
                            esSkuInfo.setHasStock(finalStockMap.get(skuInfo.getSkuId()));
                        }
                        //TODO 2.hotScore 热度评分

                        //TODO 3.查询品牌和商品分类信息
                        BrandEntity brand = brandService.getById(esSkuInfo.getBrandId());
                        esSkuInfo.setBrandName(brand.getName());
                        //catalogName
                        CategoryEntity category = categoryService.getById(esSkuInfo.getCatalogId());
                        esSkuInfo.setCatalogName(category.getName());
                        //attrs
                        esSkuInfo.setAttrs(attrsList);
                        return esSkuInfo;
                    })
                    .collect(Collectors.toList());
            log.debug("检索的sku商品信息" + esSkuInfoList);
            //将查出来的数据放到es检索里面
            R r = remoteElasticService.productStatuUp(esSkuInfoList);
            Boolean b = (Boolean) r.get("boolean");
            if (b = true) {
                UpdateWrapper<SpuInfoEntity> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", spuId);
                SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
                spuInfoEntity.setUpdateTime(new Date());
                spuInfoEntity.setPublishStatus(1);
                spuInfoService.update(spuInfoEntity, updateWrapper);
                log.debug("商品上架成功");
            } else {
                throw new RuntimeException("es服务调用失败");
            }
        }
    }

}